package com.cskaoyan.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.sql.DataSource;

/**
 * @author stone
 * @date 2022/11/12 15:04
 */
@Configuration
@ComponentScan("com.cskaoyan")
@EnableAspectJAutoProxy
public class MyBatisConfiguration {

    /*@Bean
    public SqlSessionFactory sqlSessionFactory() {
        return new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis.xml"));
    }*/
    // mybatis-spring提供了一个类，能够让我们直接注册SqlSessionFactory组件
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
    @Bean("ds1")
    public DataSource dataSource1() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/cskaoyan_db?useUnicode=true&characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    // Mapper组件
    // 提供一个类 MapperScannerConfigurer → 配置器
    // 能够封装注册Mapper组件的信息 1. Mapper接口所在的包目录 2.SqlSessionFactory组件id
    // 自动根据这些信息向容器中注册Mapper组件
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.cskaoyan.mapper");
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return configurer;
    }

    // SqlSessionFactory、DataSource、Mapper组件
}
